package com.jk.common.utils;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {
    /**
     * 从指定的URL获取输入流
     */
    public static InputStream getInputStreamFromUrl(String imageUrl) throws Exception {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 设置连接超时时间
            connection.setReadTimeout(5000);    // 设置读取超时时间

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return new BufferedInputStream(connection.getInputStream());
            }
        } catch (Exception e) {
            throw new Exception("Failed to get input stream from URL: " + imageUrl, e);
        }
        return null;
    }

    public static String getFileExtension(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return "";
        }
        int lastDotIndex = filePath.lastIndexOf('.');
        // 没有扩展名或只有点
        if (lastDotIndex == -1 || lastDotIndex == filePath.length() - 1) {
            return "";
        }
        return filePath.substring(lastDotIndex + 1);
    }

        public static void main(String[] args) {
            String imageUrl = "https://example.com/images/photo.jpg";
            String extension = getFileExtension(imageUrl);
            System.out.println("文件扩展名是: " + extension); // 输出: jpg
        }
}

